(function ($) {
    $.courseList = function () {
        return {	//书本基本信息
            courseWareGroupDTOList: [],
            pageSize: 10,
            pageIndex: 0,
            bookStatus: 0,
            pageParam: {},
            init: function () {
                this.listener();
                this.initLayui();
                this.resourceList();
            },
            /**
             * 添加各按钮所需要的监听事件
             */
            listener: function () {
                $("#searchInput").keydown(function () {
                    if (event.keyCode == 13) {
                        $.courseList.resourceList();
                    }
                });
                $("#personSearchBtn").click(function () {
                    $.courseList.resourceList();
                });
                /**
                 *点击cwp文件 进行弹窗播放
                 * **/
                $(".courseList").on("click", ".cwpIcon", function () {
                    //页面层
                    // layer.open({
                    //     type: 2,
                    //     title: '备课资料',
                    //     shadeClose: true, //开启遮罩关闭
                    //     area: ['1024px', window.innerHeight - 100 + "px"], //宽高
                    //     content: SystemConfig.openPlayView+ $(this).attr("data-fileurl")
                    // });
                    window.open(SystemConfig.openPlayView+ $(this).attr("data-fileurl"))
                });
                /**
                 *点击排序
                 * **/
                $(".courseList").on("click", ".sort", function () {
                    if ($(this).attr("data-isasc") == "2") {
                        $(this).attr("data-isasc", "1");
                        $(this).find(".icon").css("background-image", "url('img/ltb.png')");
                    } else {
                        $(this).attr("data-isasc", "2");
                        $(this).find(".icon").css("background-image", "url('img/btl.png')");
                    }
                    $.courseList.resourceList();
                });
                /**
                 *页面调整
                 * **/
                $.courseList.resize();
                $(window).resize($.courseList.resize);
                /**
                 * 监听hover事件
                 */
                $(".courseList").on("mouseover mouseout", "tbody tr", function (event) {
                    if (event.type == "mouseover") {
                        //鼠标悬浮
                        $(this).find(".controlButtons").css("display", "inline-block");
                    } else if (event.type == "mouseout") {
                        //鼠标离开
                        $(this).find(".controlButtons").css("display", "none");
                    }
                });
                /**
                 * 点击确定修改
                 */
                $(".courseList").on("click", ".dataNameEdit .icon.confirm", function () {
                    $.courseList.inputEdit($(this).prev().find("input"));
                });
                /**
                 * 监听input变化
                 */
                $(".courseList").on("blur", "input.editNameInput", function () {
                    var other = $(this).parents("tr");
                    setTimeout(function () {
                        other.find(".dataNameEdit").css("display", "none");
                        other.find(".names").css("display", "inline-block");
                    }, 500);
                    $(this).parents(".courseList").on("mouseover", "tbody tr", function () {
                        $(this).find(".controlButtons").css("display", "inline-block");
                    });
                });
                $(".courseList").on("keydown", "input.editNameInput", function () {
                    if (event.keyCode == 13) {
                        $(this).parents("tr").find(".dataNameEdit").css("display", "none");
                        $(this).parents(".courseList").on("mouseover", "tbody tr", function () {
                            $(this).find(".controlButtons").css("display", "inline-block");
                        });
                        $.courseList.inputEdit($(this));
                    }
                });
                /**
                 * 点击编辑资料名称
                 */
                $(".courseList tbody").on('click', ".editor", function () {
                    $(this).parent().css("display", "none");
                    $(this).parents(".dataCenterList").off("mouseover");
                    $(this).parent().prev().css("display", "none");
                    $(this).parents("tr").find(".dataNameEdit").css("display", "inline-block");
                    $(this).parents("tr").find(".dataNameEdit input").val($(this).parent().parent().find(".resourceName").html()).focus();
                });
                /**
                 * 课件删除一行
                 */
                $(".courseList").on('click', ".cwpDelete", function () {
                    var courseDelete = {
                        "ids": [
                            $(this).parents("tr").attr('data-id')
                        ],
                        "token": User.token
                    };
                    courseDelete = JSON.stringify(courseDelete);
                    $.courseList.deleteFile(courseDelete, Doman.courseDelete);
                });
                /**
                 * 课件删除选中行
                 */
                $(".deleteSel").on('click', function () {
                    var inputs = $(".courseList").find("tbody input[type='checkbox']:checked");
                    var ids = [];
                    if (inputs.length > 0) {
                        $.each(inputs, function (i, inputDom) {
                            ids.push($(inputDom).data('id'));
                        });
                        var courseDelete = {
                            "ids": ids,
                            "token": User.token
                        };
                        courseDelete = JSON.stringify(courseDelete);
                        $.courseList.deleteFile(courseDelete, Doman.courseDelete);
                    }else{
                        layer.msg("请点击选中项再删除");
                    }

                });

                /**
                 * ppt删除
                 */
                $(".courseList").on('click', ".pptDelete", function () {
                    var pptDelete = {
                        "pptFileId": $(this).parents("tr").attr("data-pptFileId"),
                        "token": User.token
                    };
                    pptDelete = JSON.stringify(pptDelete);
                    $.courseList.deleteFile(pptDelete, Doman.pptDelete);
                });

                /**
                 * 点击加入到
                 */
                $(".courseList").on('click', ".addTo", function () {
                    var courseWareImportDTOList = [
                        {
                            "courseWareId": $(this).parents("tr").data("id"),
                            "sequence": 0
                        }
                    ];
                    $.courseList.courseWareImport(courseWareImportDTOList);
                });
                /**
                 * 点击选择框 加入到
                 */
                $(".addToSel").on('click', function () {
                    var inputs = $(".courseList").find("tbody input[type='checkbox']:checked");
                    var courseWareImportDTOList = [];
                    if(inputs.length>0){
                        $.each(inputs, function (i, inputDom) {
                            var obj = {};
                            obj.courseWareId = $(inputDom).data("id");
                            obj.sequence = 0;
                            courseWareImportDTOList.push(obj);
                        });
                        $.courseList.courseWareImport(courseWareImportDTOList);
                    }else{
                        layer.msg("请点击选中项再加入到");
                    }
                });
                /**
                 * 点击备课资料
                 */
                $(".courseList").on('click', '.preMaterial ', function () {
                    var courseWareId = $(this).data("coursewareid");
                    layer.open({
                        type: 2,
                        title: "备课资料",
                        //closeBtn: 0, //不显示关闭按钮
                        area: ['600px', window.innerHeight - 200 + "px"],
                        content: "pageFrame/preMaterial.html?index=" + $(this).attr("data-index")
                        , btn: ['确认']
                        , yes: function (index, layero) {
                            var uploadFile = layer.getChildFrame(".uploadFile", index);
                            var docDTOs = [];
                            $.each($(uploadFile), function (i, data) {
                                docDTOs.push(data.getAttribute("href"));
                            });
                            var docDTOList = {
                                operationType: 2,//1:cwp  2:doc /ppt..资料
                                courseWareId: courseWareId,
                                docDTOs: docDTOs
                            };
                            saveObject(Doman.url + Doman.courseDoc, true, JSON.stringify(docDTOList), function (result) {
                                if (result.code == 200) {
                                    $.courseList.resourceList(true);
                                    layer.close(index);
                                }
                            });
                        }
                    });
                });
                /**
                 * 点击创建课件
                 */
                $(".createCourse").on('click', function () {
                    layer.open({
                        type: 2,
                        title: "创建课件",
                        area: ['600px', window.innerHeight - 200 + "px"],
                        content: "pageFrame/createCourse.html"
                        , btn: ['确认']
                        , yes: function (index, layero) {
                            var coursewareData = [];
                            var remarkDom = layer.getChildFrame(".remark input", index);
                            var remark = $(remarkDom).val();
                            var fileUrlDom = layer.getChildFrame(".cwpName", index);
                            var fileUrl = $(fileUrlDom).data("url");
                            var coursewareDataDom = layer.getChildFrame(".fileName", index);
                            $.each(coursewareDataDom, function (i, data) {
                                coursewareData.push($(data).data("url"));
                            });
                            var fileName = "";
                            if ($(fileUrlDom).html() != undefined) {
                                var fileNamesArr = $(fileUrlDom).html().split(".zi");
                                if (fileNamesArr.length > 1) {
                                    fileName = fileNamesArr[0];
                                }
                            }
                            var courseWareSave = {
                                "coursewareData": coursewareData,
                                "courseWareId": 0,
                                "fileUrl": fileUrl,
                                "description": remark,
                                "fileLength": 0,
                                "attachmentUrl": "",
                                "isRecord": 2,
                                "fileName": fileName,
                                "token": User.token,
                                "timeStamp": User.timeStamp
                            };
                            if (courseWareSave.fileUrl == undefined) {
                                layer.confirm('待录课件必须上传', {
                                    btn: ['确定'] //按钮
                                }, function (index, layero) {
                                    layer.close(index);
                                });
                            } else {
                                updateObject(Doman.url + Doman.courseWareSave, true, JSON.stringify(courseWareSave), function (result) {
                                    $.courseList.resourceList(true);
                                }, function () {
                                });
                                layer.close(index);
                            }
                        }
                    });
                });
                /**
                 * 点击修改课件
                 */
                $(".courseList").on('click', '.attachment', function () {
                    var courseWareId=$(this).data("id")
                    layer.open({
                        type: 2,
                        title: "修改待录课件",
                        area: ['600px', window.innerHeight - 200 + "px"],
                        content: "pageFrame/editCourse.html?pptIndex=" + $(this).data("pptindex") + "&index=" + $(this).data("index")
                        , btn: ['确认']
                        , yes: function (index, layero) {
                            var attachmentUrlDom = layer.getChildFrame(".cwpName", index);
                            var attachmentUrl=$(attachmentUrlDom).data("url");
                            var remarkDom = layer.getChildFrame(".remark input", index);
                            var remark = $(remarkDom).val();
                            var fileUrlDom = layer.getChildFrame(".cwp .delCwp", index);
                            var fileUrl="";
                            if(fileUrlDom.length!=0){
                                fileUrl= $(fileUrlDom).data("url");
                            }else{
                                fileUrl="";
                            }
                            var courseWareUpdate = {
                                "courseWareId": courseWareId,
                                "attachmentUrl": attachmentUrl,
                                "fileUrl": fileUrl,
                                "description": remark
                            };
                            updateObject(Doman.url + Doman.courseWareUpdate, true, JSON.stringify(courseWareUpdate), function (result) {
                                $.courseList.resourceList(true);
                            }, function () {
                            });
                            layer.close(index);
                        }
                    });
                });

            },
            /**
             * 页面设置高度
             * **/
            resize: function () {
                $(".courseListContent").css("height", window.innerHeight - 129 + "px");
            },
            /**
             * 加入到课程中
             * courseWareImportDTOList 数据
             * unitId 数据
             * **/
            courseWareImport: function (courseWareImportDTOList) {
                //iframe窗
                layer.open({
                    type: 2,
                    title: "自建课程",
                    //closeBtn: 0, //不显示关闭按钮
                    area: ['900px', window.innerHeight - 100 + "px"],
                    content: "pageFrame/selfList.html"
                    , btn: ['确认']
                    , yes: function (index, layero) {
                        var input = layer.getChildFrame("input[type='radio']:checked", index);
                        var unitId = $(input).data("unitid");
                        var courseWareImport = {
                            "courseWareImportDTOList": courseWareImportDTOList,
                            "unitId": unitId,
                            "token": User.token
                        };
                        updateObject(Doman.url + Doman.courseWareImport, true, JSON.stringify(courseWareImport), function (result) {
                            $.courseList.resourceList(true);
                        }, function () {
                        });
                        layer.close(index);
                    }
                });
            },
            /**
             * input修改数据
             * data 数据
             * **/
            inputEdit: function (othis) {
                othis.parents("tr").find(".dataName").css("display", "inline-block");
                othis.parents("tr").find(".dataName").next().css("display", "inline-block");
                if ($.trim(othis.val()) != "") {
                    othis.parents("tr").find(".dataName").html(othis.val());
                    var courseUpdateDes = {
                        "courseWareId": othis.parents("tr").data("id"),
                        "description": othis.val(),
                        "token": User.token
                    };
                    $.courseList.courseUpdateDes(courseUpdateDes);
                    $.courseList.resourceList(true);
                } else {
                    layer.msg("资料名称不可为空", {icon: 2});
                }
            },
            /**
             * 提交数据修改名字
             * data 数据
             * **/
            courseUpdateDes: function (data) {
                updateObject(Doman.url + Doman.courseUpdateDes, false, JSON.stringify(data), function (result) {
                    if (result.code == 200) {
                        layer.msg(result.message, {icon: 1});
                    } else {
                        layer.msg(result.message, {icon: 2});
                    }
                }, function () {
                });
            },
            /**
             * 删除确认弹出框
             * data 数据
             * url 地址
             * **/
            deleteFile: function (data, url) {
                layer.confirm('是否删除', {
                    btn: ['确定', '取消'] //按钮
                }, function (index, layero) {
                    updateObject(Doman.url + url, true, data, function (result) {
                        $.courseList.resourceList(true);
                        layer.close(index);
                    }, function () {
                    });
                }, function () {
                });
            },
            initLayui: function () {
                layui.use(['layer', 'form', 'laypage', 'table'], function () {
                    $ = layui.jquery,  layer = (parent.layer === undefined) ? layui.layer : parent.layer, form = layui.form, table = layui.table, laypage = layui.laypage;
                    form.render('checkbox');
                    //全选
                    form.on('checkbox(allChoose)', function (data) {
                        var child = $(data.elem).parents('#courseList').find('.courseList input[type="checkbox"]');
                        child.each(function (index, item) {
                            item.checked = data.elem.checked;
                        });
                        form.render('checkbox');
                    });
                });
            },
            resourceList: function (ifPage) {
                if (!ifPage) {
                    $.courseList.pageIndex = 0;
                }
                var submitData = {
                    isASC: $(".sort").attr("data-isasc"),
                    content: $("#searchInput").val(),
                    page: $.courseList.pageIndex,
                    pageSize: $.courseList.pageSize,
                    token: User.token
                };
                updateObject(Doman.url + Doman.courseList, true, JSON.stringify(submitData), function (result) {
                    //设置个人页共多少数据
                    $(".totalNum span").html(result.totalElements);
                    if (result.code=="200"&&result.courseWareGroupDTOList.length > 0) {
                        var html = "";
                        $.courseList.courseWareGroupDTOList = result.courseWareGroupDTOList;//将数据记录到全局
                        $.each(result.courseWareGroupDTOList, function (i, data) {
                            if (data.pptFileId == 0) {//如果是cwp cwep文件
                                html += $.courseList.cwpHtml(data.courseWareDTOList[0], i, 0, data.coursewareData.length, data.id);
                            } else {//如果是ppt文件
                                html += $.courseList.pptHtml(data, i);
                            }
                        });
                        $(".courseList tbody").html(html);
                        $.courseList.initLayui();
                    }else{
                        if($.courseList.pageIndex!="0"){
                            $.courseList.pageIndex=$.courseList.pageIndex-1;
                            $.courseList.resourceList(true);
                            return;
                        }else{
                            $(".courseList tbody").html("");
                            $.courseList.initLayui();
                        }
                    }
                    $.courseList.initPage(result.totalElements);
                }, function () {
                });
                $.courseList.inputEmpty();
            },
            /**
             * 拼接ppt list
             */
            pptHtml: function (data, index) {
                var html = "";
                html+='<tr data-id=' + data.id + ' data-pptFileId='+data.pptFileId+'>'
                    + '     <td>' + ($.courseList.pageIndex * $.courseList.pageSize + (index + 1)) + '</td>'
                    +'      <td>'
                    +'          <span class="pptIcon"></span>'
                    +'          <div class="names">'
                    +'              <span class="resourceName">' + data.pptFileName + '</span>'
                    +'          </div>'
                    +'          <div class="controlButtons">'
                if (data.courseWareDTOList == 0) {
                    html += '<span class="icon delete pptDelete" ></span>';
                };
                html +='          </div>'
                    +'          <div class="layui-form-item dataNameEdit">'
                    +'               <div class="layui-input-inline">'
                    +'                    <input maxlength="12" autofocus="" type="text" name="title" lay-verify="title" autocomplete="off" class="layui-input editNameInput">'
                    +'               </div>'
                    +'              <span class="icon confirm"></span>'
                    +'              <span class="icon cancel"></span>'
                    +'          </div>'
                    +'      </td>'
                    + '     <td colspan="3"></td>'
                    +'      <td><a data-index='+ index + ' data-coursewareid=' + data.id + ' class="preMaterial ' + (data.coursewareData.length > 0 ? "blue" : "") + '">备课资料</a></td>'
                    +'</tr>';

                if (data.courseWareDTOList.length > 0) {
                    var coursewareid = data.id;
                    $.each(data.courseWareDTOList, function (i, data) {
                        html += $.courseList.cwpHtml(data, i, ($.courseList.pageIndex * $.courseList.pageSize + (index + 1)), 0, coursewareid);
                    });
                }
                return html;
            },
            /**
             * 拼接cwp cwep list
             */
            cwpHtml: function (data, index, PptCwpIndex, hasCourseware, coursewareid) {
                var html = "";
                html += '<tr data-id=' + data.id + '>';
                if (PptCwpIndex == 0) {
                    html += '<td><input data-id=' + data.id + ' type="checkbox"  name=""  lay-skin="primary" title=' + ($.courseList.pageIndex * $.courseList.pageSize + (index + 1)) + '></td>';
                } else {
                    html += '<td class="isPptCwp"><input data-id=' + data.id + ' type="checkbox"   name="" lay-skin="primary" title=' + PptCwpIndex + '-' + (index + 1) + '></td>';
                }
                var isRecordHtml='"';
                if(data.isRecord == 1){//如果是cwp文件 则显示cwpIcon 及data-fileurl显示链接地址
                    isRecordHtml='cwpIcon" data-fileurl='+data.fileUrl;
                }
                html+='<td>'
                    + '    <span class="cwepIcon '+ isRecordHtml + '></span>'
                    + '    <div class="names">'
                    + '        <span class="resourceName" title=' + data.description + '>' + data.description + '</span>'
                    +'     </div>'
                    +'     <div class="controlButtons">'
                    +'         <span class="icon editor"></span>'
                    +'         <span class="icon addTo"></span>'
                    +'         <span class="icon delete cwpDelete"></span>'
                    +'     </div>'
                    +'     <div class="layui-form-item dataNameEdit">'
                    +'         <div class="layui-input-inline">'
                    +'              <input maxlength="12" autofocus="" type="text" name="title" lay-verify="title" autocomplete="off" class="layui-input editNameInput">'
                    +'          </div>'
                    +'          <span class="icon confirm"></span>'
                    +'          <span class="icon cancel"></span>'
                    +'      </div>'
                    + '</td>'
                    +  '<td>' + changeTime(data.fileLength) + '</td>'
                    +  '<td>'
                    +  '    <span class="attachment" data-index=' + index + ' data-id=' + data.id + ' data-pptindex=' + (PptCwpIndex == 0 ? "" :( PptCwpIndex - 1-$.courseList.pageIndex * $.courseList.pageSize)) + '></span>'
                    +  '</td>'
                    +  '<td>' + changeDate(data.createTime) + '</td>';
                if (PptCwpIndex == 0) {
                    html+='<td><a data-index=' + index + ' data-coursewareid=' + coursewareid + ' class="preMaterial ' + (hasCourseware == 0 ? "" : "blue") + '">备课资料</a></td>';
                }else{
                    html+='<td></td>';
                }
                html += '</tr>';
                return html;
            },
            inputEmpty:function(){
                //引用完成后input全置为空
                $("input[type='checkbox']").attr("checked",false);
                $.each($("input[type='checkbox']"),function(i,inputs){
                    $(inputs).attr("checked",false);
                    $.courseList.initLayui();
                });
            },
            /**
             * 初始化分页页码
             * @returns
             */
            initPage: function (total) {
                layui.use(['laypage'], function () {
                    var $ = layui.jquery, layer = layui.layer, laypage = layui.laypage;
                    laypage.render({
                        elem: 'pagination'
                        , count: total //数据总数，从服务端得到
                        , first: '首页'
                        , last: '尾页'
                        , layout: ['prev', 'page', 'next', 'skip', 'limit']
                        , curr: $.courseList.pageIndex+1
                        , limit: $.courseList.pageSize
                        , skip: true
                        , theme: '#337ab7'
                        , jump: function (obj, first) {
                            $.courseList.pageIndex = obj.curr-1;
                            $.courseList.pageSize = obj.limit;
                            //首次不执行
                            if (!first) {
                                $.courseList.resourceList(true);
                            }
                        }
                    });
                });

            }
        }
    }();
    $.courseList.init();
})(jQuery);